package cn.piggy.gateway.core.socket.handler;

import cn.piggy.gateway.core.config.ConfigHelper;
import cn.piggy.gateway.core.http.HttpStatement;
import cn.piggy.gateway.core.socket.common.AgreementConstant;
import cn.piggy.gateway.core.socket.common.GatewayResult;
import cn.piggy.gateway.core.socket.parser.RequestParser;
import cn.piggy.gateway.core.socket.parser.ResponseParser;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class GatewayServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    private final Logger logger = LoggerFactory.getLogger(GatewayServerHandler.class);

    private final ConfigHelper configHelper;

    public GatewayServerHandler(ConfigHelper configHelper) {
        this.configHelper = configHelper;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) throws Exception {
        Channel channel = ctx.channel();
        // todo record log
        logger.info("网关接收请求【全局】 uri：{} method：{}", request.uri(), request.method());
        try {
            // 1. 解析参数
            RequestParser requestParser = new RequestParser(request);
            String uri = requestParser.getUri();

            // 2. 保存信息；HttpStatement、Header=token
            HttpStatement httpStatement = configHelper.getHttpStatement(uri);
            channel.attr(AgreementConstant.HTTP_STATEMENT).set(httpStatement);

            // 3. 放行服务
            request.retain();
            ctx.fireChannelRead(request);
        } catch (Exception e) {
            // 4. 封装返回结果
            DefaultFullHttpResponse response = new ResponseParser().parse(GatewayResult.buildError(AgreementConstant.ResponseCode._500.getCode(),
                    "网关协议调用失败！" + e.getMessage()));
            channel.writeAndFlush(response);
        }
    }
}